# -*- coding:utf-8 -*-
import random
import time

from PageClass import EcsIndexPage, EcsMyApprovalPage, EcsApprovalDetailPage
from TestCases.common._baseClass import _BaseClass
from TestCases.common.loginDepend import LoginDepend
from Util import logger, ZTCCLOUDError, config


class BusinessApprove(_BaseClass):

    def __init__(self, boeNo, user, driver=None, isExit: bool = False):
        self.isExit = isExit
        self.boeNo = boeNo
        if driver:
            self.driver = driver
            self.driver.get(config.urlDict.url.ecsHost)
        else:
            self.login = LoginDepend('ecsHost', user)
            self.driver = self.login.driver
        self._ecsIndexPage = EcsIndexPage(self.driver)
        self._ecsMyApprovalPage = EcsMyApprovalPage(self.driver)
        self._ecsApprovalDetailPage = EcsApprovalDetailPage(self.driver)
        if not self._ecsIndexPage.waitElementLoading():
            raise ZTCCLOUDError('30秒内费用报销首页未加载完成')
        self._ecsIndexPage.click_myWaitApprove()
        self._ecsIndexPage.click_moreButton()
        self.__findBoe()
        self.__enterBoeDetail()

    def __exit__(self, *args):
        if super().__exit__(*args):
            if self.isExit:
                self.exit()
        else:
            self.exit()

    def exit(self):
        self.driver.quit()

    def __findBoe(self):
        self._ecsMyApprovalPage.input_boeNo(self.boeNo)
        sTime = time.time()
        while True:
            eTime = time.time()
            self._ecsMyApprovalPage.click_boeNoSelectButton()
            try:
                status = self._ecsMyApprovalPage.selectResultIsOrNotBusiness(self.boeNo)
            except:
                pass
            else:
                if status:
                    break
            if eTime - sTime >= 600:
                raise TimeoutError(f"{self.boeNo} do not exist，待我审批10分钟未找到单据")
        if not status:
            raise ZTCCLOUDError(f"{self.boeNo} do not exist，待我审批未找到匹配单据")

    def __enterBoeDetail(self):
        self._ecsMyApprovalPage.click_boeNoToDetail()

    def __isOrNotSuccess(self):
        boxMessage = self._ecsApprovalDetailPage.getToastBoxText()
        if ('处理成功' in boxMessage) or ('当前已无更多审批单据' in boxMessage):
            content = '审批成功'
            logger.info(f"审批状态为：{content}")
            return content
        else:
            content = '审批失败'
            logger.info(f"审批状态为：{content}")
            return content

    def __boxIsOrNotSuccess(self):
        boxMessage = self._ecsApprovalDetailPage.getBoxMessage()
        if ('处理成功' in boxMessage) or ('当前已无更多审批单据' in boxMessage):
            content = '审批成功'
            logger.info(f"审批状态为：{content}")
            return content
        else:
            content = '审批失败'
            logger.info(f"审批状态为：{content}")
            return content

    def __hangIsOrNotSuccess(self):
        boxMessage = self._ecsApprovalDetailPage.getBoxMessage2()
        if ('成功' in boxMessage) or ('当前已无更多审批单据' in boxMessage):
            content = '审批成功'
            logger.info(f"审批状态为：{content}")
            return content
        else:
            content = '审批失败'
            logger.info(f"审批状态为：{content}")
            return content

    # 审批拒绝
    def boeBusinessApproveReject(self, nodeName, approvalComment, isSendToMe: bool = False):
        try:
            self._ecsMyApprovalPage.input_approvalComment(approvalComment)
            self._ecsMyApprovalPage.click_boeBusinessReject()
            self._ecsMyApprovalPage.select_rejectNode(nodeName)
            if isSendToMe:
                self._ecsMyApprovalPage.select_switch()
            self._ecsMyApprovalPage.click_submit()
            return self.__isOrNotSuccess()
        except Exception as e:
            logger.error(f"业务审批拒绝出现异常，异常信息为：{str(e)}")

    # 审批同意
    def boeBusinessApprove(self):
        try:
            self._ecsMyApprovalPage.click_boeBusinessApprove()
            # self._ecsMyApprovalPage.click_boeBusinessTipConfirm()
            return self.__isOrNotSuccess()
        except Exception as e:
            logger.error(f"业务审批同意出现异常，异常信息为：{str(e)}")

    # 加签
    def boeBusinessApproveAddSign(self, signLocation, approvalOptions, *signPersonArgs):
        """
            业务审批-加签
            加签人说明：根据传入的参数进行多选，若单选请传入[{'key1': 'value1', 'key2': 'value2'}]
        :param signLocation: 加签位置
        :param approvalOptions: 审批意见
        :param signPersonArgs: 加签人，格式[{},{}]，例如：[{'登录账号': '123'}, {'员工名称': '名称1'}]
        :return: None
        """
        try:
            self._ecsApprovalDetailPage.move_toDropDown()
            self._ecsApprovalDetailPage.click_addSignButton()
            # 加签位置
            self._ecsApprovalDetailPage.click_signLocation()
            self._ecsApprovalDetailPage.select_signLocation(signLocation)
            # 加签人
            self._ecsApprovalDetailPage.click_signPerson()
            self._ecsApprovalDetailPage.selectValueFromMultiTable(*signPersonArgs)
            # 审批意见
            self._ecsApprovalDetailPage.input_options(approvalOptions)
            self._ecsApprovalDetailPage.click_submitButton()
            return self.__boxIsOrNotSuccess()
        except Exception as e:
            logger.error(f"业务审批加签出现异常，异常信息为：{str(e)}")

    # 转交
    def boeBusinessApproveTransfer(self, approvalComment, **transferPerson):
        try:
            self._ecsMyApprovalPage.input_approvalComment(approvalComment)
            self._ecsApprovalDetailPage.move_toDropDown()
            self._ecsApprovalDetailPage.click_transferButton()
            # 点击转交人按钮
            self._ecsApprovalDetailPage.click_transferLocationButton()
            # 选择转交人
            self._ecsApprovalDetailPage.selectTransferPerson(**transferPerson)
            # 点击提交
            self._ecsApprovalDetailPage.click_transferSubmit()
            return self.__boxIsOrNotSuccess()
        except Exception as e:
            logger.error(f"业务审批转交出现异常，异常信息为：{str(e)}")

    # 挂起
    def boeBusinessApproveHangUp(self):
        try:
            self._ecsApprovalDetailPage.move_toDropDown()
            self._ecsApprovalDetailPage.click_hangUpButton()
            self._ecsApprovalDetailPage.click_hangUpConfirm()
            return self.__hangIsOrNotSuccess()
        except Exception as e:
            logger.error(f"业务审批挂起出现异常，异常信息为：{str(e)}")

    # 解挂
    def boeBusinessApproveHangOut(self):
        try:
            self._ecsApprovalDetailPage.move_toDropDown()
            self._ecsApprovalDetailPage.click_hangOutButton()
            self._ecsApprovalDetailPage.click_hangOutConfirm()
            return self.__hangIsOrNotSuccess()
        except Exception as e:
            logger.error(f"业务审批解挂出现异常，异常信息为：{str(e)}")

    def __actionApproveBoe(self, action, **kwargs):
        content = ''
        if action == '同意':
            content = self.boeBusinessApprove()
        elif action == '驳回':
            reject = kwargs.get('reject')
            content = self.boeBusinessApproveReject(reject.get('nodeName'),
                                                    reject.get('approvalComment'),
                                                    reject.get('isSendToMe', False))
        elif action == '转交':
            transfer = kwargs.get('transfer')
            content = self.boeBusinessApproveTransfer(transfer.get('approvalComment'),
                                                      **transfer.get('transferPerson'))
        elif action == '挂起':
            content = self.boeBusinessApproveHangUp()
        elif action == '解挂':
            content = self.boeBusinessApproveHangOut()
        elif action == '加签':
            sign = kwargs.get('sign')
            content = self.boeBusinessApproveAddSign(sign.get('signLocation'),
                                                     sign.get('approvalOptions'),
                                                     *sign.get('signPersonArgs'))
        self._ecsMyApprovalPage.switchToWindow(self._ecsMyApprovalPage.getWindowHandles()[2])
        return content

    # 打开两个标签页，第一个做一种操作，第二个做另一种操作
    def boeBusinessApproveTwoPages(self, action1, action2, **kwargs):
        try:
            self._ecsMyApprovalPage.copyCurrentPageToAnotherPage()
            self.__actionApproveBoe(action1, **kwargs)
            return self.__actionApproveBoe(action2, **kwargs)
        except Exception as e:
            logger.error(f"业务审批第一个{action1}，第二个{action2}出现异常，异常信息为：{str(e)}")
